package net.osc.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.osc.dao.HibernateDao;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

public class BaseController {

	private static final Log logger = LogFactory.getLog(BaseController.class);

	@Resource
	protected HibernateDao hibernateDao;

	public HibernateDao getHibernateDao() {
		return hibernateDao;
	}

	public void setHibernateDao(HibernateDao hibernateDao) {
		this.hibernateDao = hibernateDao;
	}

	@ExceptionHandler
	@ResponseBody
	public String onException(HttpServletRequest req, HttpServletResponse resp, Exception ex)
			throws Exception {
		logger.error(ex.getMessage(), ex);
		resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		ObjectMapper om = new ObjectMapper();
		return om.writeValueAsString(new JsonResult(ex));
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

}
